package com.atguigu.gulimall.ware.rabbit.config;

import com.atguigu.gulimall.ware.rabbit.constant.WareConstant;
import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description
 * @Author lhj
 * @Date 2024/5/18 14:23
 */
@Configuration
public class RabbitConfig {

    /**
     * 声明topic交换机
     * @return
     */
    @Bean
    public TopicExchange stockEventExchange() {
        return new TopicExchange(WareConstant.STOCK_EVENT_EXCHANGE, true, false);
    }

    /**
     * 声明延迟队列
     * @return
     */
    @Bean
    public Queue stockDelayQueue() {
        Map<String, Object> arguments = new HashMap<>();
        arguments.put("x-dead-letter-exchange", WareConstant.STOCK_EVENT_EXCHANGE);
        arguments.put("x-dead-letter-routing-key", WareConstant.STOCK_RELEASE_QUEUE);
        arguments.put("x-message-ttl", 120000);
        return QueueBuilder.durable(WareConstant.STOCK_DELAY_QUEUE).withArguments(arguments).build();
    }

    /**
     * 声明解锁库存队列
     * @return
     */
    @Bean
    public Queue stockReleaseQueue() {
        return QueueBuilder.durable(WareConstant.STOCK_RELEASE_QUEUE).build();
    }
    
    /**
     * 延迟队列绑定
     * @param stockEventExchange 交换机
     * @param stockDelayQueue 延迟队列
     * @return
     */
    @Bean
    public Binding stockDelayBinding(@Qualifier(value = "stockEventExchange") TopicExchange stockEventExchange,
                                     @Qualifier(value = "stockDelayQueue") Queue stockDelayQueue) {
        return BindingBuilder.bind(stockDelayQueue).to(stockEventExchange).with(WareConstant.STOCK_DELAY_ROUTING_KEY);
    }
    
    @Bean
    public Binding stockReleaseBinding(@Qualifier(value = "stockEventExchange") TopicExchange stockEventExchange,
                                       @Qualifier(value = "stockReleaseQueue") Queue stockReleaseQueue) {
        return BindingBuilder.bind(stockReleaseQueue).to(stockEventExchange).with(WareConstant.STOCK_RELEASE_ROUTING_KEY);
    }

    /**
     * 订单释放解锁库存队列绑定
     * @return
     */
    @Bean
    public Binding orderReleaseOtherBinding() {
        return new Binding(
                WareConstant.STOCK_RELEASE_QUEUE,
                Binding.DestinationType.QUEUE,
                WareConstant.ORDER_EVENT_EXCHANGE,
                WareConstant.ORDER_RELEASE_OTHER_ROUTING_KEY,
                null
        );
    }
    
}
